package com.asktgapp.user.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.asktgapp.JGTool.Utils;
import com.asktgapp.R;
import com.asktgapp.application.ApiUtil;
import com.asktgapp.application.Apiservice;
import com.asktgapp.architecture.retrofit.ApiException;
import com.asktgapp.architecture.retrofit.ApiResponseBody;
import com.asktgapp.architecture.rxjava.ExceptionHandle;
import com.asktgapp.base.BaseFragment;
import com.asktgapp.eventbus.HomeServiceItemEvent;
import com.asktgapp.model.ServiceOrderItemVO;
import com.asktgapp.modulebase.common.adapter.BaseAdapter;
import com.asktgapp.modulebase.common.adapter.BaseViewHolder;
import com.asktgapp.modulebase.common.util.PreferencesUtil;
import com.asktgapp.modulebase.common.util.Util;
import com.asktgapp.user.activity.HomeServiceDetailActivity;
import com.asktgapp.utils.ImageDisplayUtil;
import com.asktgapp.widget.RefreshRecyclerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 上门服务普通用户订单
 */

public class ServiceOrderUserFragment extends BaseFragment {

    RefreshRecyclerView mRefreshRecyclerView;
    private RecyclerView mRecyclerView;
    private BaseAdapter mBaseAdapter;
    private int mPage = 1;
    private int type=0;//1.已支付 0.未支付

    public static ServiceOrderUserFragment newInstance() {
        ServiceOrderUserFragment fragment = new ServiceOrderUserFragment();
        Bundle bundle = new Bundle();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.freshrecyclerview, container, false);
        EventBus.getDefault().register(this);
        return super.onCreateView(inflater, viewGroup, savedInstanceState);
    }

    @Override
    protected void initView(View rootView) {
        getBaseActivity().setBackNavigationIcon();
        mRefreshRecyclerView = rootView.findViewById(R.id.recycle);
        mRecyclerView = mRefreshRecyclerView.getRecyclerView();
        mRefreshRecyclerView.setRefreshAction(new RefreshRecyclerView.Action() {
            @Override
            public void onAction(int page) {
                mPage = page;
                getData();
            }
        });
        mRefreshRecyclerView.setLoadMoreAction(new RefreshRecyclerView.Action() {
            @Override
            public void onAction(int page) {
                mPage = page;
                getData();
            }
        });
        mBaseAdapter = new BaseAdapter(getActivity()) {
            @Override
            public BaseViewHolder getViewHolder(ViewGroup parent, int viewType) {
                BaseViewHolder holder = new BaseViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.item_home_service, parent, false),
                        new BaseViewHolder.Callbacks2() {
                            @Override
                            public void bind(final BaseViewHolder holder, Object data) {
                                if (data instanceof ServiceOrderItemVO) {
                                    final ServiceOrderItemVO bean = (ServiceOrderItemVO) data;
                                    final ImageView head = holder.getView(R.id.userHead);
                                    ImageDisplayUtil.loadCircleHeadImage(getActivity(), head, bean.getUserPic());
                                    holder.setText(R.id.userName, bean.getUserName());
                                    holder.setText(R.id.serviceContent, bean.getServiceInfo());
                                    Date date = Util.StrToDate(bean.getAddTime(), "yyyy.MM.dd HH:mm:ss");
                                    String timeStr = Utils.getAskTime(date);
                                    holder.setText(R.id.addTime, timeStr);
                                    String pro = bean.getProviceName().replaceAll("省", "");
                                    String city = bean.getCityName().replaceAll("市", "");
                                    if (TextUtils.isEmpty(pro + " " + city))
                                        holder.setText(R.id.serviceAddress, "未知地区");
                                    else
                                        holder.setText(R.id.serviceAddress,pro+" "+city);

                                    holder.getView(R.id.serviceStatus).setVisibility(View.VISIBLE);
                                    if(bean.getState().equals("0")){
                                        holder.setText(R.id.serviceStatus,"未支付");
                                    }else {
                                        holder.setText(R.id.serviceStatus,"已支付");
                                    }
                                    ImageDisplayUtil.loadCircleHeadImage(getActivity(),head,  bean.getUserPic());
                                    String type = bean.getType();
                                    String serviceType = "维修";
                                    if(type.equals("1")){
                                        serviceType =("维修");
                                    }else if(type.equals("2")){
                                        serviceType =("检车");
                                    }else if(type.equals("3")){
                                        serviceType =("保养");
                                    }else if(type.equals("4")){
                                        serviceType =("评估");
                                    }
                                    holder.setText(R.id.serviceType,serviceType);

                                }
                            }

                            @Override
                            public void onItemClick(BaseViewHolder holder, View view, int position) {
                                ServiceOrderItemVO b = (ServiceOrderItemVO) mBaseAdapter.getData(position);
                                Intent intent = new Intent(getActivity(), HomeServiceDetailActivity.class);
                                intent.putExtra("id", b.getId());
                                getActivity().startActivity(intent);
                            }
                        });

                return holder;
            }
        }

        ;
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        mRecyclerView.setAdapter(mBaseAdapter);
    }

    @Override
    public void loadData() {
        visibleLoading();
        mPage = 1;
        getData();
    }

    private void getData() {
        HashMap params = new HashMap();
        params.put("userId", PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID));
        params.put("page", mPage);
        params.put("isPay", type);

        Apiservice apiservice = ApiUtil.getInstance().create();

        Call<ApiResponseBody<List<ServiceOrderItemVO>>> call = apiservice.userOrderList(params);
        call.enqueue(new Callback<ApiResponseBody<List<ServiceOrderItemVO>>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<List<ServiceOrderItemVO>>> call, Response<ApiResponseBody<List<ServiceOrderItemVO>>> response) {
                inVisibleLoading();
                if (mRefreshRecyclerView == null) {
                    Log.i("JGAPP", "mRefreshRecyclerView == null");
                    return;
                }
                Log.i("JGAPP", " 调用了接口");
                mRefreshRecyclerView.endPage();
                if (response.isSuccessful()) {
                    List<ServiceOrderItemVO> list = response.body().getResult();
                    if (mPage == 1) {
                        if (list == null || list.size() == 0) {
                            visibleNoData();
                        } else {
                            mBaseAdapter.setData(list);
                            mRefreshRecyclerView.showNextMore(mPage);
                        }
                    } else {
                        if (list == null || list.size() == 0) {
                            mRefreshRecyclerView.showNoMore();
                        } else {
                            mBaseAdapter.addData(BaseAdapter.AddType.LASE, list);
                            mRefreshRecyclerView.showNextMore(mPage);
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<List<ServiceOrderItemVO>>> call, Throwable t) {
                inVisibleLoading();
                if (mRefreshRecyclerView == null) {
                    Log.i("JGAPP", "mRefreshRecyclerView == null");
                    return;
                }
                Log.i("JGAPP", " 调用了接口");
                mRefreshRecyclerView.endPage();
                ApiException apiException = ExceptionHandle.handleException(t);
                if (apiException.isTokenInvalid()) {
                    showUnLoginSnackbar();
                } else if (apiException.isNetConnected()) {
                    showSetNetworkSnackbar();
                } else {
                    showTost(apiException.getMessage(), 0);
                }

            }
        });


    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void a(HomeServiceItemEvent b) {
        if (b.getType()) {
            mPage = 1;
            getData();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
